<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/10/31
 * Time: 14:09
 */
namespace app\api\service;
use think\Db;
use think\Exception;
use think\log;
require_once BASE_ROOT."core/application/common.php";
require_once BASE_ROOT."core/application/admin/service/PrinterService.php";
require_once BASE_ROOT."core/application/api/service/RefundService.php";
use app\api\service\RefundService;
use app\admin\service\PrinterService;
class OrderService
{
    private $o='ybsc_order';
    private $uc='ybsc_user_coupon';
    private $s='ybsc_goods_sku';
    private $g='ybsc_goods';
    private $op='ybsc_order_payment';
    private $i='ybsc_images';
    private $og='ybsc_order_goods';
    private $dq='ybsc_area';
    private $u='ybsc_user';
    private $os='ybsc_order_share';
    private $usm='ybsc_user_share_money';
    // private $cf='ybsc_config';
    public function Print_test($mch_id,$oid){
        $pp = new PrinterService($mch_id,$oid,'order',0);
        $info=$pp->print_order();
        return json_encode($info);
    }
    /**
     * 生成订单
     * @param $data
     * @return mixed|null
     */
    public function createOrder($data)
    {
        // 启动事务
        Db::startTrans();
        try {
            $data_new=$data;
            unset($data_new['sku_id']);
            $data_new['finish_time']=0;
            $data_new['refund_time']=0;
            $data_new['consign_time']=0;
            $data_new['seller_memo']='';
            $order_id=Db::name($this->o)->insertGetId($data_new);
            if($order_id){
                //订单打印
                $pp = new PrinterService($data['mch_id'],$order_id,'order',0);
                $pp->print_order();
            }
            //优惠券标记使用
            if($data['coupon_id']!=0){
                $coupon_data = array(
                    'status'=>1,
                    'use_time' => time()
                );
                Db::name($this->uc)->where('id',$data['coupon_id'])->update($coupon_data);
            }
            //获取商品信息
            $sku_id  = rtrim($data['sku_id'],",");
            $sku = explode( ',',$sku_id);
            $goods_num=0;
            $share_goods_id=0;
            if(count($sku)==1){
                $goods_num=1;
            }
            foreach ($sku as $value)
            {
                //根据sku_id 查询数据
                $value_data = explode( ':',$value);
                $data_sku = Db::name($this->s)->where("sku_id",$value_data[0])->find();
                //检测库存
                if($data_sku['stock'] <= 0)
                {
                    throw new Exception('库存不足');
                }
                //获取商品id,用于计算单商品佣金
                if($goods_num==1){
                    $share_goods_id=$data_sku['goods_id'];
                }
                //获取商品名称
                $data_goods = Db::name($this->g)->where("goods_id",$data_sku['goods_id'])->find();
                //修改商品销量
                Db::name($this->g)->where("goods_id",$data_sku['goods_id'])->setInc('real_sales', $value_data[1]);
                Db::name($this->g)->where("goods_id",$data_sku['goods_id'])->setInc('sales', $value_data[1]);
                //修改商品库存
                Db::name($this->g)->where("goods_id",$data_sku['goods_id'])->setDec('stock', $value_data[1]);
                //修改对应sku库存
                Db::name($this->s)->where("sku_id",$value_data[0])->setDec('stock', $value_data[1]);
                //如果sku不存在图片
                if($data_sku->images == 0)
                {
                    $images = $data_goods['images'];
                }
                else
                {
                    $images = $data_sku['images'];
                }
                $goods_data = [
                    'order_id' => $order_id,
                    'sku_id' => $value_data[0],
                    'sku_name' => $data_sku['sku_name'],
                    'goods_id' => $data_sku['goods_id'],
                    'goods_name' => $data_goods['goods_name'],
                    'price' => $value_data[1] * $data_sku['price'],
                    'num' => $value_data[1],
                    'goods_money' => $data_sku['price'],
                    'goods_images' => $images,
                    'buyer_id' => $data['buyer_id'],
                ];
                //订单商品
                Db::name($this->og)->insert($goods_data);
            }
            //创建支付订单
            $pay_data = array(
                'out_trade_no'  => $data['out_trade_no'],
                'pay_type'  => $data['pay_type'],
                'type_alis_id'  => $order_id,
                'pay_body'      => "用户支付",
                'pay_detail'    => "用户购买商品",
                'pay_money'     => $data['pay_money'],
                'pay_status'=>0,
                'pay_time'=>0,
                'create_time'   => time()
            );
            Db::name($this->op)->insert($pay_data);
            //创建分销订单
            $u=Db::name($this->u)->where('uid',$data['buyer_id'])->find();
            $pid=$u['pid']?$u['pid']:0;
            $pid_db=$this->is_distributor($pid);//判断是否分销商
            $pid1=$pid;
            if($pid_db!=1){
                $pid1=0;
            }
            $setting=$this->get_shareSetting($data['mch_id'],$share_goods_id);//获取分销配置信息
            $fx_data=array(
                'user_id'=>$data['buyer_id'],
                'order_id'=>$order_id,
                'first_price'=>0,
                'second_price'=>0,
                'third_price'=>0,
                'parent_id_1'=>$pid1,
                'parent_id_2'=>0,
                'parent_id_3'=>0,
                'is_del'=>1,
                'rebate'=>0,
                'mch_id'=>$data['mch_id'],
                'create_time'=>time()
            );
            if ($setting && $setting['level'] != 0) {
                if ($setting['price_type'] == 0) {//按比例--佣金
                    $fx_data['first_price'] = floatval($data['pay_money']) * floatval($setting['first']) / 100;
                    $fx_data['second_price'] = floatval($data['pay_money']) * floatval($setting['second']) / 100;
                    $fx_data['third_price'] = floatval($data['pay_money']) * floatval($setting['third']) / 100;
                } else {//按金额--佣金
                    $fx_data['first_price'] = $setting['first'];
                    $fx_data['second_price'] = $setting['second'];
                    $fx_data['third_price'] = $setting['third'];
                }
                if ($u['is_distributor'] && $setting['is_rebate'] == 1) {//分销商自购返利；佣金同一级分销
                    $fx_data['rebate'] = $fx_data['first_price'];
                }
                if ($setting['level'] == 1) {//一级分销
                    if ($pid1 != 0 || $fx_data['rebate'] != 0) {//没有上线，自购返利
                        Db::name($this->os)->insert($fx_data);
                    }
                } elseif ($setting['level'] == 2) {//二级分销

                    $pid2 = $this->get_user_uid($pid);
                    $pid_db2 = $this->is_distributor($pid2);//判断是否分销商
                    if ($pid_db2 != 1) {
                        $pid2 = 0;
                    }
                    if ($pid1 != 0 || $pid2 != 0 || $fx_data['rebate'] != 0) {
                        $fx_data['parent_id_2'] = $pid2;
                        Db::name($this->os)->insert($fx_data);
                    }
                } elseif ($setting['level'] == 3) {//三级分销
                    $pid2 = $this->get_user_uid($pid);
                    $pid_db2 = $this->is_distributor($pid2);//判断是否分销商
                    $pid3 = $this->get_user_uid($pid2);
                    $pid_db3 = $this->is_distributor($pid3);//判断是否分销商
                    if ($pid_db2 != 1) {
                        $pid2 = 0;
                    }
                    $fx_data['parent_id_2'] = $pid2;
                    if ($pid_db3 != 1) {
                        $pid3 = 0;
                    }
                    if ($pid1 != 0 || $pid2 != 0 || $pid3 != 0 || $fx_data['rebate'] != 0) {
                        $fx_data['parent_id_3'] = $pid3;
                        Db::name($this->os)->insert($fx_data);
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::write('生成订单失败 --(用户id：' . $data['buyer_id'].') 错误信息：'.$e->getMessage(),'order_error');
            return ['err_code'=>1,'msg'=>$e->getMessage()];
        }
        return ['err_code'=>0,'info'=>$order_id];
    }
    public function get_shareSetting($mch_id,$share_goods_id){
        $info=Db::name('ybsc_user_share_setting')->where('mch_id',$mch_id)->find();
        if($share_goods_id<>0){//若设置了单商品分销，则佣金为单商品所设置
            $goods_share=Db::name('ybsc_goods_share_setting')->where(['mch_id'=>$mch_id,'goods_id'=>$share_goods_id,'status'=>1])->find();
            if($goods_share){
                $info['price_type']=$goods_share['price_type'];
                $info['first']=$goods_share['first'];
                $info['second']=$goods_share['second'];
                $info['third']=$goods_share['third'];
            }
        }
        return $info;
    }
    /**
     * 是否分销商
     * @param $uid
     * @return mixed
     */
    public function is_distributor($uid){
        if($uid==0){
            return 0;
        }
        $a=Db::name($this->u)->where(['uid'=>$uid])->value('is_distributor');
        if($a){
            return $a;
        }else{
            return 0;
        }
    }
    /**
     * 获取用户上一级uid
     * @param $uid
     * @return mixed
     */
    public function get_user_uid($uid){
        if($uid==0){
            return 0;
        }
        $pid=Db::name($this->u)->where(['uid'=>$uid])->value('pid');
        if($pid){
            return $pid;
        }else{
            return 0;
        }
    }
    /**
     * 用户订单列表
     * @param $data
     * @param $page
     * @return false|null|\PDOStatement|string|\think\Collection
     */
    public function orderList($data,$page = 1)
    {
        $order_list = null;
        $order_list =
            Db::name($this->o)->where($data)
                ->where("is_deleted",0)
                ->page($page, PAGE_NUM)
                ->order('create_time', 'desc')
                ->select();
        if(empty($order_list))
        {
            return $order_list;
        }
        foreach ($order_list as $key => $value)
        {
            //时间戳
//            $value['sign_time']  = __TIME($value['sign_time']);
            $order_list[$key]['paytime']  = $this->LTIME( $value['pay_time']);
//            $value['consign_time']  = __TIME($value['consign_time']);
            $goods = Db::name($this->og)->where('order_id',$value['order_id'])->select();
            foreach ($goods as $k=>$v)
            {
                $pic = Db::name($this->i)->where("img_id",$v['goods_images'])
                    ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
                    ->find();
                if($pic)
                {
                    $goods[$k]['pic'] = $pic;
                }
            }
            $order_list[$key]["have_log"]=$this->check_log($value["order_id"],1);
            $order_list[$key]['goods']=$goods;
        }
        return $order_list;
    }
    public function check_log($order,$type=1){
        $res=Db::name("ybsc_order_refund")->where(["order_id"=>$order,"type"=>$type])->count();
        return $res;
    }
    public function LTIME($time)
    {
        $date = "";
        if (! empty($time)) {
            $date = date("Y-m-d H:i:s",$time) ;
        }
        return $date;
    }
    /**
     * 用户单条订单信息
     * @param $data
     * @return array|false|null|\PDOStatement|string|\think\Model
     */
    public function getOrder($data)
    {
        $order_info = null;
        $order_info =
            Db::name($this->o)->where($data)
                ->where("is_deleted",0)
                ->find();
        if(empty($order_info))
        {
            return $order_info;
        }
        //时间戳
        $order_info['sign_time']  = __TIME($order_info['sign_time']);
        $order_info['pay_time']  = __TIME($order_info['pay_time']);
        $order_info['consign_time']  = __TIME($order_info['consign_time']);
        $order_info['create_time']  = __TIME($order_info['create_time']);
        $order_info['mention_time']  = __TIME($order_info['mention_time']);
        //地址
        $res=Db::name($this->dq)->where('id',$order_info['receiver_area'])->find();
        $city=Db::name($this->dq)->where('id',$res['pid'])->find();
        $pro=Db::name($this->dq)->where('id',$city['pid'])->find();
        $address['province']= $pro['name'];
        $address['city']=$city['name'];
        $address['district']=$res['name'];
        $order_info['address'] = $address;
        //商品
        $order_info['goods'] = Db::name($this->og)->where('order_id',$order_info['order_id'])->select();
        //图片
        foreach ($order_info['goods'] as $k=>$v)
        {
            $pic = Db::name($this->i)->where("img_id",$v['goods_images'])
                ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
                ->find();
            if($pic)
            {
                $order_info['goods'][$k]['pic'] = $pic;
            }
        }
        //物流
        $order_info['express']=0;
        $express=Db::name('ybsc_order_express')->where(['shipping_type'=>1,'order_type'=>0,'order_id'=>$order_info['order_id']])->find();
        if(!empty($express) && $express['express_company'] && $express['express_no']){
            $order_info['express']=1;
            $order_info['express_company']=$express['express_company'];
            $order_info['express_no']=$express['express_no'];
        }
        //客服
//        $cse = Db::name($this->cf)->where(['key' => "CSE","mch_id"=>$data['mch_id']])
//            ->find();
//        $order_info['cse'] = json_decode($cse['value'],true);
        return $order_info;
    }
    /**
     * 用户签收订单
     * @param $data
     * @return false|int
     */
    public function signOrder($data)
    {
        $rs = array('code' => 0,'info' => array());
        Db::startTrans();
        try {
            $new_data = array('order_status'=> 3,'sign_time'=>time());
            $info= Db::name($this->o)->where($data)->update($new_data);
            if(empty($info))
            {
                throw new Exception('操作失败');
            }
            $us=Db::name($this->os)->where(['user_id'=>$data['buyer_id'],'order_id'=>$data['order_id']])->find();
            if($us){
                $share_data=[
                    'mch_id'=>$data['mch_id'],
                    'order_id'=>$data['order_id'],
                    //  'type'=>0,
                    'create_time'=>time(),
                    'is_del'=>1
                ];
                if($us['parent_id_1'] && $us['parent_id_1']!=0){//一级分销商佣金记录
                    $share_data['user_id']=$us['parent_id_1'];
                    $share_data['money']=$us['first_price'];
                    $share_data['source']=1;
                    Db::name($this->usm)->insert($share_data);
                    Db::name($this->u)->where('uid',$us['parent_id_1'])->setInc('total_price', $us['first_price']);
                    Db::name($this->u)->where('uid',$us['parent_id_1'])->setInc('price', $us['first_price']);
                }
                if($us['parent_id_2'] && $us['parent_id_2']!=0){//二级分销商佣金记录
                    $share_data['user_id']=$us['parent_id_2'];
                    $share_data['money']=$us['second_price'];
                    $share_data['source']=2;
                    Db::name($this->usm)->insert($share_data);
                    Db::name($this->u)->where('uid',$us['parent_id_2'])->setInc('total_price', $us['second_price']);
                    Db::name($this->u)->where('uid',$us['parent_id_2'])->setInc('price', $us['second_price']);
                }
                if($us['parent_id_3'] && $us['parent_id_3']!=0){//三级分销商佣金记录
                    $share_data['user_id']=$us['parent_id_3'];
                    $share_data['money']=$us['third_price'];
                    $share_data['source']=3;
                    Db::name($this->usm)->insert($share_data);
                    Db::name($this->u)->where('uid',$us['parent_id_3'])->setInc('total_price', $us['third_price']);
                    Db::name($this->u)->where('uid',$us['parent_id_3'])->setInc('price', $us['third_price']);
                }
                if($us['rebate'] && $us['rebate']!=0){//分销商佣金记录
                    $share_data2=[
                        'mch_id'=>$data['mch_id'],
                        'order_id'=>$data['order_id'],
                        'create_time'=>time(),
                        'is_del'=>1
                    ];
                    $share_data2['user_id']=$us['user_id'];
                    $share_data2['money']=$us['rebate'];
                    $share_data2['source']=1;
                    Db::name($this->usm)->insert($share_data);
                    Db::name($this->u)->where('uid',$us['user_id'])->setInc('total_price', $us['rebate']);
                    Db::name($this->u)->where('uid',$us['user_id'])->setInc('price', $us['rebate']);
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $rs['code']=1;
            $rs['msg']=$e->getMessage();
            return json_encode($rs);
        }
        //订单打印
        $pp = new PrinterService($data['mch_id'],$data['order_id'],'confirm',0);
        $pp->print_order();
        $rs['info'] =$info;
        return json_encode($rs);
    }
    /**
     * 取消订单
     * @param $data
     * @return false|int
     */
    public function cancelOrder($data)
    {
        //订单信息
        $info  =Db::name($this->o)->where($data)->find();
        if(empty($info))
        {
            return null;
        }
        //订单商品
        $order_goods_info = Db::name($this->og)->where("order_id",$data['order_id'])->select();
        Db::startTrans();
        try {
            //修改订单状态
            $new_data = array('order_status'=> -1);
            $res = Db::name($this->o)->where(['order_id'=>$data['order_id']])->update($new_data);
            //恢复库存
            foreach ($order_goods_info as $key =>$value)
            {
                //恢复商品库存
                Db::name($this->g)->where("goods_id",$value['goods_id'])->setInc('stock', $value['num']);
                //恢复对应sku库存
                Db::name($this->s)->where("sku_id",$value['sku_id'])->setInc('stock', $value['num']);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
        return $res;
    }
    /**
     * 订单删除
     * @param $data
     * @return false|int|null
     */
    public function delOrder($data)
    {
        $info  =Db::name($this->o) ->where($data)->find();
        if(empty($info))
        {
            return null;
        }
        $new_data = array('is_deleted'=> 1);
        $res = Db::name($this->o)->where(['order_id'=>$data['order_id']])->update($new_data);
        return $res;
    }
    /**
     * 订单退款
     * @param $data
     * @return false|int|null
     */
    public function refundOrder($data,$apply_refund)
    {
        $info  = Db::name($this->o)->where($data)->find();
        if(empty($info))
        {
            return null;
        }
        $new_data = array('order_status'=> 4,'refund_time'=>time());
        $res = Db::name($this->o)->where(['order_id'=>$data['order_id']])->update($new_data);
        if($res && $apply_refund){
            $refund=new RefundService();
            $refund->refundLog($info['mch_id'],$info['buyer_id'],$apply_refund,$info['order_id'],1);
        }
        return $res;
    }
    public function RefundList($data){
        $list=Db::name('ybsc_order_refund')->where($data)->order('id desc')->select();
        if(!empty($list)){
            foreach($list as $k=>$v){
                if($v['apply_time']){
                    $list[$k]['apply_time']=Date('Y-m-d H:i',$v['apply_time']);
                }
                if($v['create_time']){
                    $list[$k]['create_time']=Date('Y-m-d H:i',$v['create_time']);
                }
            }
        }
        return $list;
    }
}